package com.qsl.ssyx.payment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qsl.ssyx.client.order.OrderFeignClient;
import com.qsl.ssyx.common.exception.BusinessException;
import com.qsl.ssyx.common.result.ResultCodeEnum;
import com.qsl.ssyx.enums.PaymentStatus;
import com.qsl.ssyx.enums.PaymentType;
import com.qsl.ssyx.model.order.OrderInfo;
import com.qsl.ssyx.model.order.PaymentInfo;
import com.qsl.ssyx.payment.mapper.PaymentInfoMapper;
import com.qsl.ssyx.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 支付信息表 服务实现类
 * </p>
 *
 * @author 青衫泪
 * @since 2023-09-11
 */
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Autowired
    private OrderFeignClient orderFeignClient;

    // 根据商品唯一id查询支付记录表是否有此订单
    @Override
    public PaymentInfo getPaymentInfoByOrderNo(String orderNo) {
        LambdaQueryWrapper<PaymentInfo> lqw = new LambdaQueryWrapper<>();
        lqw.eq(PaymentInfo::getOrderNo, orderNo);
        PaymentInfo paymentInfo = baseMapper.selectOne(lqw);
        return paymentInfo;
    }


    // 根据orderNo（订单号）查询订单信息,并根据订单信息新增订单支付表
    @Override
    public PaymentInfo savePaymentInfo(String orderNo) {
        // 根据orderNo（订单号）查询订单信息
        OrderInfo orderInfo = orderFeignClient.getOrderInfoByorderNo(orderNo);
        if (orderInfo == null) {
            throw new BusinessException(ResultCodeEnum.DATA_ERROR);
        }
        // 封装到订单支付表
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setOrderId(orderInfo.getId());
        paymentInfo.setPaymentType(PaymentType.WEIXIN); // 支付类型-微信
        paymentInfo.setUserId(orderInfo.getUserId());
        paymentInfo.setOrderNo(orderInfo.getOrderNo());
        paymentInfo.setPaymentStatus(PaymentStatus.UNPAID); // 支付状态-支付中
        paymentInfo.setSubject("userID:" + orderInfo.getUserId() + "下订单");// 交易内容
        //paymentInfo.setTotalAmount(orderInfo.getTotalAmount());
        paymentInfo.setTotalAmount(new BigDecimal("0.001")); // 支付金额

        // 订单支付表-新增
        baseMapper.insert(paymentInfo);
        return paymentInfo;
    }


}
